package com.lykj.llw.box.ui.diafrg

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.isseiaoki.simplecropview.FreeCropImageView
import com.lykj.lib_base.base.BaseDiaFrg
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.custom.imageload.GlideImageLoader
import com.lykj.llw.box.data.bean.response.UploadResponse
import com.lykj.llw.box.databinding.DiafrgBottomPicPickerBinding
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.lzy.imagepicker.view.CropImageView
import io.reactivex.disposables.Disposable
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * ================================================
 * 底部图片获取方式弹窗
 * ================================================
 *
 * @author gosha
 * @date 2023/10/25-15:22
 */
class BottomPicPickerDiaFrg : BaseDiaFrg() {
    lateinit var binding: DiafrgBottomPicPickerBinding

    private val REQUEST_CODE_SELECT = 100
    private var mUserType = 0//0:用户 1:代理

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DiafrgBottomPicPickerBinding.inflate(layoutInflater)

        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun onStart() {
        super.onStart()

        val window = dialog!!.window
        //设置窗口弹出动画
        window!!.setWindowAnimations(0)
        window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val layoutParams = window.attributes
        layoutParams.apply {
            dimAmount = 0.5f
            gravity = Gravity.BOTTOM
            width = WindowManager.LayoutParams.MATCH_PARENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
        }


        if (null != dialog) {
            val dm = DisplayMetrics()
            requireActivity().windowManager.defaultDisplay.getMetrics(dm)
            dialog?.apply {
                setCanceledOnTouchOutside(true)
                window.setGravity(Gravity.BOTTOM)
            }
        }
    }

    override fun initUI() {
        initImagePicker()
    }

    private fun initImagePicker() {
        ImagePicker.getInstance().apply {
            imageLoader = GlideImageLoader() //设置图片加载器
            isShowCamera = true //显示拍照按钮
            isCrop = false //允许裁剪（单选才有效）
            isSaveRectangle = true //是否按矩形区域保存
            selectLimit = 1 //选中数量限制
            style = CropImageView.Style.RECTANGLE //裁剪框的形状
            focusWidth = 800 //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
            focusHeight = 800 //裁剪框的高度。单位像素（圆形自动取宽高最小值）
            outPutX = 1000 //保存文件的宽度。单位像素
            outPutY = 1000
        }
    }

    //设置用户类型
    open fun setUserType(userType: Int): BottomPicPickerDiaFrg {
        mUserType = userType
        return this
    }

    //修改头像
    private fun editAvatar(url: String) {
        clearBodyParam()
        initBodyParam()
        bodyParams["avatar"] = url
        RetrofitManager.instance.editUserInfo(
            bodyParams,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this, d)
                }

                override fun specificHandle(responseBody: String) {
                    ToastUtils.showShort(requireContext(), "修改头像成功")
                    FlowBus.with<String>("UpdateAvatar").post(requireActivity().lifecycleScope, url)
                    dismiss()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(requireContext(), it)
                    }
                }
            })
    }

    private fun editAgentAvatar(url: String) {
        clearBodyParam()
        initBodyParam()
        bodyParams["headPic"] = url
        RetrofitManager.instance.editAgentAvatarNickName(
            bodyParams,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this, d)
                }

                override fun specificHandle(responseBody: String) {
                    ToastUtils.showShort(requireContext(), "修改头像成功")
                    FlowBus.with<String>("UpdateAgentAvatar").post(requireActivity().lifecycleScope, url)
                    dismiss()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(requireContext(), it)
                    }
                }
            })
    }

    //上传图片
    private fun uploadPic(filePath: String) {
        RetrofitManager.instance
            .uploadSingleFile("${BConstants.RELEASE_URL}/upload/files", filePath, "image/jpeg")
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    LogUtils.e("上传图片失败")
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        val str = response.body?.string()
                        val bean = GsonUtils.fromJson(str, UploadResponse::class.java)

                        LogUtils.e("上传完的图片地址:${bean.data}")
                        //修改头像
                        if (mUserType == 0) {
                            editAvatar(bean.data)
                        } else {
                            editAgentAvatar(bean.data)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
    }

    /**
     * Uri转File
     */
    private fun getRealFilePath(context: Context, uri: Uri): String? {
        if (null == uri) {
            return null
        }
        val scheme: String = uri.scheme!!
        var data: String? = null
        if (scheme == null) {
            data = uri.path
        } else if (ContentResolver.SCHEME_FILE == scheme) {
            data = uri.path
        } else if (ContentResolver.SCHEME_CONTENT == scheme) {
            val cursor: Cursor? = context.contentResolver
                .query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null)
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.tvBtnCamera.clickWithTrigger(300) {
            //打开选择,本次允许选择的数量
            ImagePicker.getInstance().selectLimit = 1
            ImagePicker.getInstance().isMultiMode = false
            ImagePicker.getInstance().setFreeCrop(true, FreeCropImageView.CropMode.FREE)
            val intent = Intent(
                requireContext(),
                ImageGridActivity::class.java
            )
            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true) // 是否是直接打开相机

            startActivityForResult(
                intent,
                REQUEST_CODE_SELECT
            )
        }
        binding.tvBtnGallery.clickWithTrigger(300) {
            //打开选择,本次允许选择的数量
            ImagePicker.getInstance().selectLimit = 1
            ImagePicker.getInstance().isMultiMode = true
            val intent = Intent(
                requireContext(),
                ImageGridActivity::class.java
            )

            startActivityForResult(
                intent,
                REQUEST_CODE_SELECT
            )
        }
        binding.tvBtnCancel.clickWithTrigger(300) {
            dismiss()
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                val images =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                if (images != null) {
                    LogUtils.e("选择图片返回:${images[0].uri}")


                    //开始上传
                    getRealFilePath(requireContext(), images[0].uri)?.let {
                        uploadPic(it)
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}